import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Card, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  List, 
  Space,
  Row,
  Col,
  Divider,
  Typography,
  Spin,
  Empty,
  message,
  Image
} from 'antd';
import { 
  LikeOutlined, 
  LikeFilled,
  CommentOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  ArrowLeftOutlined,
  UserOutlined
} from '@ant-design/icons';
import type { Post, Comment } from '../../types';
import './PostDetail.scss';

const { TextArea } = Input;
const { Title, Paragraph, Text } = Typography;

const PostDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [post, setPost] = useState<Post | null>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [recommendedPosts, setRecommendedPosts] = useState<Post[]>([]);
  const [commentContent, setCommentContent] = useState('');
  const [isLiked, setIsLiked] = useState(false);
  const [submittingComment, setSubmittingComment] = useState(false);

  // 模拟帖子数据
  const mockPost: Post = {
    id: '1',
    title: '期末考试复习方法分享',
    content: `马上就要期末考试了，分享一下我的复习方法，希望对大家有帮助。

首先，我们需要根据考试时间和科目数量，制定一个详细的复习计划。建议大家使用番茄工作法，每次专注学习25分钟，然后休息5分钟。

不同的科目需要不同的复习方法：
• 数学：多做题，总结题型和解题方法
• 英语：背单词，做阅读理解，练习写作
• 专业课：理解概念，构建知识体系

根据老师划的重点和历年考题，有针对性地进行复习。把重点内容整理成思维导图，方便记忆。

在考试前一周，进行几次模拟考试，熟悉考试节奏，提高答题速度。

复习期间一定要保证充足的睡眠，不要熬夜。良好的身体状态是取得好成绩的基础。

希望这些方法对大家有帮助，祝大家考试顺利！`,
    images: [
      'https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?w=800',
      'https://images.unsplash.com/photo-1434030216411-0b793f4b4173?w=800',
      'https://images.unsplash.com/photo-1523240795612-9a054b0db644?w=800',
    ],
    author: { id: '1', username: '学霸小王', email: 'xiaowang@example.com', role: 'student' },
    category: 'discussion',
    tags: ['学习', '考试', '复习方法'],
    createdAt: '2024-01-15T10:30:00Z',
    updatedAt: '2024-01-15T10:30:00Z',
    likes: 45,
    comments: 23,
    views: 256,
  };

  // 模拟评论数据
  const mockComments: Comment[] = [
    {
      id: '1',
      postId: '1',
      content: '太实用了！感谢分享，我准备按照这个方法试试看。',
      author: { id: '2', username: '小李', email: 'xiaoli@example.com', role: 'student' },
      createdAt: '2024-01-15T11:00:00Z',
      likes: 5,
    },
    {
      id: '2',
      postId: '1',
      content: '番茄工作法真的很有效，我一直在用。不过我觉得休息时间可以稍微长一点，10分钟比较合适。',
      author: { id: '3', username: '学习达人', email: 'xuexidaren@example.com', role: 'student' },
      createdAt: '2024-01-15T12:30:00Z',
      likes: 8,
    },
    {
      id: '3',
      postId: '1',
      content: '请问有没有推荐的复习资料？',
      author: { id: '4', username: '小张', email: 'xiaozhang@example.com', role: 'student' },
      createdAt: '2024-01-15T14:20:00Z',
      likes: 2,
    },
  ];

  // 模拟推荐帖子
  const mockRecommendedPosts: Post[] = [
    {
      id: '2',
      title: 'React Hooks 使用心得',
      content: '最近在学习React Hooks，发现useEffect的使用有很多细节需要注意...',
      images: ['https://images.unsplash.com/photo-1633356122544-f134324a6cee?w=400'],
      author: { id: '4', username: '前端新手', email: 'frontend@example.com', role: 'student' },
      category: 'discussion',
      tags: ['学习', 'React', '前端'],
      createdAt: '2024-01-14T16:30:00Z',
      updatedAt: '2024-01-14T16:30:00Z',
      likes: 34,
      comments: 18,
      views: 189,
    },
    {
      id: '3',
      title: '大学英语四级备考攻略',
      content: '分享一下我的四级备考经验，希望能帮到正在准备的同学们...',
      author: { id: '5', username: '英语小能手', email: 'english@example.com', role: 'student' },
      category: 'discussion',
      tags: ['学习', '英语', '四级'],
      createdAt: '2024-01-14T10:00:00Z',
      updatedAt: '2024-01-14T10:00:00Z',
      likes: 52,
      comments: 31,
      views: 412,
    },
    {
      id: '4',
      title: '如何高效管理学习时间',
      content: '时间管理对于大学生来说非常重要，我总结了几个方法...',
      images: [
        'https://images.unsplash.com/photo-1484480974693-6ca0a78fb36b?w=400',
        'https://images.unsplash.com/photo-1506784983877-45594efa4cbe?w=400',
      ],
      author: { id: '6', username: '时间管理大师', email: 'time@example.com', role: 'student' },
      category: 'discussion',
      tags: ['学习', '时间管理', '效率'],
      createdAt: '2024-01-13T15:20:00Z',
      updatedAt: '2024-01-13T15:20:00Z',
      likes: 28,
      comments: 12,
      views: 178,
    },
  ];

  useEffect(() => {
    loadPostDetail();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const loadPostDetail = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setPost(mockPost);
      setComments(mockComments);
      setRecommendedPosts(mockRecommendedPosts);
    } catch (error) {
      console.error('加载帖子详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = () => {
    setIsLiked(!isLiked);
    if (post) {
      setPost({
        ...post,
        likes: isLiked ? post.likes - 1 : post.likes + 1,
      });
    }
  };

  const handleSubmitComment = async () => {
    if (!commentContent.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    setSubmittingComment(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newComment: Comment = {
        id: String(comments.length + 1),
        postId: id!,
        content: commentContent,
        author: { id: 'current', username: '当前用户', email: 'current@example.com', role: 'student' },
        createdAt: new Date().toISOString(),
        likes: 0,
      };

      setComments([newComment, ...comments]);
      setCommentContent('');
      message.success('评论发布成功');
      
      // 更新评论数
      if (post) {
        setPost({ ...post, comments: post.comments + 1 });
      }
    } catch (error) {
      console.error('发布评论失败:', error);
      message.error('评论发布失败');
    } finally {
      setSubmittingComment(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const getTagColor = (tag: string) => {
    const colors = {
      '学习': 'blue',
      '日常': 'green',
      '吐槽': 'red',
      '考试': 'purple',
      'React': 'cyan',
      '英语': 'orange',
      '四级': 'gold',
      '时间管理': 'magenta',
      '效率': 'lime',
    };
    return colors[tag as keyof typeof colors] || 'default';
  };

  const handleRecommendedPostClick = (postId: string) => {
    navigate(`/posts/discussion/${postId}`);
    window.scrollTo(0, 0);
  };

  if (loading) {
    return (
      <div className="post-detail-loading">
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!post) {
    return (
      <div className="post-detail-empty">
        <Empty description="帖子不存在" />
        <Button type="primary" onClick={() => navigate(-1)} style={{ marginTop: 16 }}>
          返回
        </Button>
      </div>
    );
  }

  return (
    <div className="post-detail-page">
      <div className="page-header">
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate(-1)}
          type="text"
        >
          返回
        </Button>
      </div>

      <Row gutter={24} className="post-detail-content">
        {/* 左侧：帖子内容 */}
        <Col xs={24} lg={14}>
          <Card className="post-content-card">
            <div className="post-header">
              <Title level={2}>{post.title}</Title>
              <div className="post-meta">
                <Space>
                  <Avatar size="small" icon={<UserOutlined />} />
                  <Text strong>{post.author.username}</Text>
                  <Text type="secondary">
                    <ClockCircleOutlined /> {formatDate(post.createdAt)}
                  </Text>
                </Space>
              </div>
              <div className="post-tags">
                {post.tags.map((tag, index) => (
                  <Tag key={index} color={getTagColor(tag)}>
                    {tag}
                  </Tag>
                ))}
              </div>
            </div>

            <Divider />

            <div className="post-body">
              {/* 帖子内容 */}
              <div className="post-text-content">
                {post.content.split('\n').map((line, index) => {
                  if (line.trim() === '') {
                    return <br key={index} />;
                  }
                  return <Paragraph key={index}>{line}</Paragraph>;
                })}
              </div>

              {/* 图片展示 */}
              {post.images && post.images.length > 0 && (
                <div className="post-images">
                  <Image.PreviewGroup>
                    <Row gutter={[12, 12]}>
                      {post.images.map((image, index) => (
                        <Col 
                          key={index}
                          xs={24}
                          sm={post.images!.length === 1 ? 24 : 12}
                          md={post.images!.length === 1 ? 24 : post.images!.length === 2 ? 12 : 8}
                        >
                          <Image
                            src={image}
                            alt={`图片 ${index + 1}`}
                            className="post-image"
                            placeholder={
                              <div className="image-placeholder">
                                <Spin />
                              </div>
                            }
                          />
                        </Col>
                      ))}
                    </Row>
                  </Image.PreviewGroup>
                </div>
              )}
            </div>

            <Divider />

            <div className="post-footer">
              <Space size="large">
                <Button 
                  type={isLiked ? 'primary' : 'default'}
                  icon={isLiked ? <LikeFilled /> : <LikeOutlined />}
                  onClick={handleLike}
                >
                  {post.likes}
                </Button>
                <span>
                  <CommentOutlined /> {post.comments} 评论
                </span>
                <span>
                  <EyeOutlined /> {post.views} 浏览
                </span>
              </Space>
            </div>
          </Card>
        </Col>

        {/* 右侧：评论区 */}
        <Col xs={24} lg={10}>
          <Card className="comments-card" title={`评论 (${comments.length})`}>
            <div className="comment-input-section">
              <TextArea
                rows={4}
                placeholder="写下你的评论..."
                value={commentContent}
                onChange={(e) => setCommentContent(e.target.value)}
                maxLength={500}
                showCount
              />
              <Button 
                type="primary" 
                onClick={handleSubmitComment}
                loading={submittingComment}
                style={{ marginTop: 12 }}
              >
                发布评论
              </Button>
            </div>

            <Divider />

            <div className="comments-list">
              {comments.length > 0 ? (
                <List
                  dataSource={comments}
                  renderItem={(comment) => (
                    <List.Item key={comment.id}>
                      <List.Item.Meta
                        avatar={<Avatar icon={<UserOutlined />} />}
                        title={
                          <Space>
                            <Text strong>{comment.author.username}</Text>
                            <Text type="secondary" style={{ fontSize: 12 }}>
                              {formatDate(comment.createdAt)}
                            </Text>
                          </Space>
                        }
                        description={
                          <div>
                            <Paragraph style={{ marginBottom: 8 }}>{comment.content}</Paragraph>
                            <Button 
                              type="text" 
                              size="small" 
                              icon={<LikeOutlined />}
                            >
                              {comment.likes}
                            </Button>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <Empty description="暂无评论" image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </div>
          </Card>
        </Col>
      </Row>

      {/* 下方：推荐帖子 */}
      <div className="recommended-posts-section">
        <Card title="推荐阅读" className="recommended-posts-card">
          <Row gutter={[16, 16]}>
            {recommendedPosts.map((recommendedPost) => (
              <Col xs={24} sm={12} lg={8} key={recommendedPost.id}>
                <Card 
                  hoverable 
                  className="recommended-post-item"
                  onClick={() => handleRecommendedPostClick(recommendedPost.id)}
                  cover={
                    recommendedPost.images && recommendedPost.images.length > 0 ? (
                      <div className="recommended-post-cover">
                        <img 
                          src={recommendedPost.images[0]} 
                          alt={recommendedPost.title}
                        />
                        {recommendedPost.images.length > 1 && (
                          <div className="image-count-badge">
                            {recommendedPost.images.length} 图
                          </div>
                        )}
                      </div>
                    ) : null
                  }
                >
                  <Title level={5} ellipsis={{ rows: 2 }}>
                    {recommendedPost.title}
                  </Title>
                  <Paragraph 
                    ellipsis={{ rows: 2 }} 
                    type="secondary"
                    style={{ fontSize: 13 }}
                  >
                    {recommendedPost.content}
                  </Paragraph>
                  <div className="recommended-post-meta">
                    <Space size="small" split={<Divider type="vertical" />}>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        <UserOutlined /> {recommendedPost.author.username}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        <LikeOutlined /> {recommendedPost.likes}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        <CommentOutlined /> {recommendedPost.comments}
                      </Text>
                    </Space>
                  </div>
                  <div className="recommended-post-tags">
                    {recommendedPost.tags.map((tag, index) => (
                      <Tag key={index} color={getTagColor(tag)}>
                        {tag}
                      </Tag>
                    ))}
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      </div>
    </div>
  );
};

export default PostDetail;

